package com.example.adminservice.controller;

import com.example.adminservice.dto.BookAuditDto;
import com.example.adminservice.dto.ChapterAuditDto;
import com.example.adminservice.entity.Admin;
import com.example.adminservice.entity.BookAudit;
import com.example.adminservice.entity.ChapterAudit;
import com.example.adminservice.service.AdminService;
import com.example.adminservice.service.BookAuditService;
import com.example.commom.enums.RespDescEnum;
import com.example.commom.enums.StatusCodeEnum;
import com.example.commom.page.PageInfo;
import com.example.commom.redis.RedisUtils;
import com.example.commom.utils.AdminVerifyUtils;
import com.example.commom.utils.JwtUtils;
import com.example.feign.client.BookClient;
import com.example.feign.result.AjaxResult;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 软工2104-李家强-2100770248
 * @since 2023-09-28
 */

@Transactional
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminVerifyUtils adminVerifyUtils;

    @Autowired
    private AdminService adminService;

    @Autowired
    private BookClient bookClient;



    @GetMapping("/{id}")
    @ApiOperation(value = "通过id获取管理员信息", notes = "通过id获取管理员信息")
    public AjaxResult getUserById(@PathVariable("id") Long id,
                                  @RequestHeader(value = "token", required = false) String token) {
        return AjaxResult.success(adminService.getById(id));
    }

    /**
     *  管理员登录接口
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口", notes = "参数是: username, password")
    public AjaxResult login(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            @RequestHeader(value = "token", required = false) String userToken) {
        // 参数非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(RespDescEnum.MissRequiredParameter.getValue());
        }

        // 查询数据库, 查看用户名是否正确
        Admin admin = adminService.getUserByName(username);
        if (admin == null) {
            return AjaxResult.fail(StatusCodeEnum.FAILED.getCode(), RespDescEnum.AccountNotExistence.getValue());
        }

        // 判断账号是否被封禁
        if (!admin.getIsAvailable()) {
            return AjaxResult.fail(StatusCodeEnum.FAILED.getCode(), RespDescEnum.AccountIsBanned.getValue());
        }

        // 检查密码
        if (!admin.getPassword().equals(password)) {
            return AjaxResult.fail(StatusCodeEnum.FAILED.getCode(),RespDescEnum.AccountVerifyFailed.getValue());
        }

        // 判定多开
        String redisToken = RedisUtils.getJwtTokenFromRedis(
                RedisUtils.getTokenRedisKey(admin.getType(), admin.getAdminId())
        );
        if (redisToken != null) {
            if (!redisToken.equals(userToken)) {
                return AjaxResult.fail(StatusCodeEnum.FAILED.getCode(), RespDescEnum.AccountIsLogin.getValue());
            }
        }

        // 正常的账号, 进行登录
        HashMap<String, Object> result = adminService.successLogin(admin);

        return AjaxResult.success(StatusCodeEnum.OK.getCode(), result);
    }

    /**
     *  退出登录
     */
    @PostMapping("/exit")
    @ApiOperation(value = "退出登录", notes = "参数无")
    public AjaxResult exit(@RequestHeader("token") String token) {

        return adminService.exit(token);
    }



    /**
     *  管理员获取全部的未审核的图书[新发布的书籍/修改过书籍信息的书籍]
     */
    @PostMapping("/approved/book/false")
    @ApiOperation(value = "管理员获取全部的未审核的图书", notes = "参数无")
    public AjaxResult getApprovedBookFalse(@RequestHeader("token") String token,
                                       @RequestBody PageInfo pageInfo) {

        return bookClient.getApprovedBookFalse(token, pageInfo.getPageSize(), pageInfo.getPageNum());
    }

    /**
     *  获取未审核的章节列表
     */
    @PostMapping("/approved/chapter/false")
    @ApiOperation(value = "管理员获取全部的未审核的图书", notes = "参数无")
    public AjaxResult getApprovedChapterFalse(@RequestHeader("token") String token,
                                       @RequestBody PageInfo pageInfo) {

        return bookClient.getApprovedChapterFalse(token, pageInfo.getPageSize(), pageInfo.getPageNum());
    }

    /**
     *  审核书籍
     */
    @PostMapping("/approve/books")
    @ApiOperation(value = "管理员审核书籍", notes = "管理员审核书籍")
    public AjaxResult approveBook(@Validated @RequestBody BookAuditDto bookAuditDto,
                                  @RequestHeader("token") String token) {

        // 1. 权限校验
        boolean flag = adminVerifyUtils.verity(token);
        if (!flag) {
            return AjaxResult.fail(StatusCodeEnum.UNAUTHORIZED.getCode(), StatusCodeEnum.UNAUTHORIZED.getMsg());
        }

        // 2. 判断书籍 id 是否正确, 只能是管理员能做到!
        boolean correct = bookClient.isCorrectBookId(bookAuditDto.getBookId(), token);
        if (!correct) {
            return AjaxResult.fail(StatusCodeEnum.FAILED.getMsg());
        }

        BookAudit bookAudit = new BookAudit();
        Long adminId = Long.parseLong(JwtUtils.getUserIdByToken(token) + "");
        bookAudit.setAdminId(adminId);
        BeanUtils.copyProperties(bookAuditDto, bookAudit);

        return adminService.approveBook(bookAudit);
    }

    /**
     *  审核章节
     */
    @PostMapping("/approve/chapters")
    @ApiOperation(value = "管理员审核章节", notes = "管理员审核章节")
    public AjaxResult approveChapter(@Validated @RequestBody ChapterAuditDto chapterAuditDto,
                                     @RequestHeader("token") String token) {

        // 1. 权限校验
        boolean flag = adminVerifyUtils.verity(token);
        if (!flag) {
            return AjaxResult.fail(StatusCodeEnum.UNAUTHORIZED.getCode(), StatusCodeEnum.UNAUTHORIZED.getMsg());
        }

        // 2. 判断章节 id 是否正确, 只能是管理员能做到!
        boolean correct = bookClient.isCorrectChapterId(chapterAuditDto.getChapterId(), token);
        if (!correct) {
            return AjaxResult.fail(StatusCodeEnum.FAILED.getMsg());
        }

        ChapterAudit chapterAudit = new ChapterAudit();
        Long adminId = Long.parseLong(JwtUtils.getUserIdByToken(token) + "");
        chapterAudit.setAdminId(adminId);
        BeanUtils.copyProperties(chapterAuditDto, chapterAudit);

        return adminService.approveChapter(chapterAudit);
    }


    /**
     *  验证 id 是否是 管理员 id
     */
    @GetMapping("/verify/{id}")
    @ApiOperation(value = "查询指定id是不是管理员", notes = "参数为id")
    public boolean verifyIsAdmin(@PathVariable("id") Long id) {
        Admin admin = adminService.getById(id);
        if (admin == null)
            return false;

        return admin.getIsAvailable();
    }


    /**
     *  书籍历史审核记录
     */
    @PostMapping("/approve/book/history")
    @ApiOperation(value = "书籍历史审核记录", notes = "书籍历史审核记录")
    public AjaxResult getBookHistory(@RequestHeader("token") String token,
                                     @RequestBody PageInfo pageInfo) {

        return adminService.getBookHistory(token, pageInfo);
    }

    /**
     *  章节历史审核记录
     */
    @PostMapping("/approve/chapter/history")
    @ApiOperation(value = "书籍历史审核记录", notes = "书籍历史审核记录")
    public AjaxResult getChapterHistory(@RequestHeader("token") String token,
                                     @RequestBody PageInfo pageInfo) {

        return adminService.getChapterHistory(token, pageInfo);
    }

}
